<template>
  <div class="progress-center">
    <h1 class="page-title">进度中心</h1>

    <!-- 时间范围选择 -->
    <el-card class="content-card filter-card" shadow="hover">
      <el-form :inline="true">
        <el-form-item label="快捷选择">
          <el-select v-model="quickSelect" @change="handleQuickSelect" placeholder="选择时间范围" style="width: 150px">
            <el-option label="近1周" value="1week" />
            <el-option label="近1个月" value="1month" />
            <el-option label="近3个月" value="3months" />
            <el-option label="近半年" value="6months" />
            <el-option label="近1年" value="1year" />
          </el-select>
        </el-form-item>
        <el-form-item label="自定义时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            @change="handleDateChange"
            style="width: 260px"
          />
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 能力发展曲线 -->
    <el-card class="content-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>能力发展曲线</span>
          <div class="header-actions">
            <el-select v-model="selectedDomain" placeholder="全部领域" clearable style="width: 150px; margin-right: 10px">
              <el-option label="全部领域" value="" />
              <el-option
                v-for="item in domainOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
        </div>
      </template>

      <div v-loading="loadingCurve" class="chart-container" ref="chartRef"></div>
    </el-card>

    <!-- 各领域完成率统计 -->
    <el-card class="content-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>各领域完成率统计</span>
        </div>
      </template>

      <div v-loading="loadingStats" class="stats-container">
        <el-row :gutter="20">
          <el-col
            v-for="stat in domainStats"
            :key="stat.domain"
            :xs="24"
            :sm="12"
            :md="8"
            :lg="8"
          >
            <div class="domain-stat-card">
              <div class="stat-header">
                <h3>{{ stat.domainName }}</h3>
                <el-progress
                  type="circle"
                  :percentage="Math.round(stat.completionRate)"
                  :width="80"
                  :color="getProgressColor(stat.completionRate)"
                />
              </div>
              <div class="stat-details">
                <div class="stat-item">
                  <span class="label">已完成</span>
                  <span class="value">{{ stat.completed }}</span>
                </div>
                <div class="stat-item">
                  <span class="label">总任务</span>
                  <span class="value">{{ stat.total }}</span>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 快速访问 -->
    <el-card class="content-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>快速访问</span>
        </div>
      </template>

      <div class="quick-actions">
        <el-button type="primary" @click="goToTaskHistory">
          <el-icon><Clock /></el-icon>
          查看历史记录
        </el-button>
        <el-button type="success" @click="goToGrowthBox">
          <el-icon><Box /></el-icon>
          查看成长盒
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted, nextTick, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { getMultiDomainCurve, getDomainStats } from '@/api/progress'
import { DOMAIN_OPTIONS } from '@/utils/constants'
import * as echarts from 'echarts'
import dayjs from 'dayjs'

const router = useRouter()
const userStore = useUserStore()

const loadingCurve = ref(false)
const loadingStats = ref(false)
const chartRef = ref()
let chartInstance = null

const quickSelect = ref('1month')
const dateRange = ref([])
const selectedDomain = ref('')
const domainOptions = DOMAIN_OPTIONS
const domainStats = ref([])
const curveData = ref(null)

// 领域颜色配置
const domainColors = {
  social: '#ffb3d9',         // 社交能力 - 粉色
  emotion: '#ffc299',        // 情绪管理 - 橙色
  selfcare: '#b3e5d9',       // 生活自理 - 青色
  communication: '#ffcccc',  // 沟通交流 - 浅红
  cognition: '#d9b3ff',      // 认知能力 - 紫色
  motor: '#99d9ea'           // 行为干预 - 浅蓝
}

const domainNames = {
  social: '社交能力',
  emotion: '情绪管理',
  selfcare: '生活自理',
  communication: '沟通交流',
  cognition: '认知能力',
  motor: '行为干预'
}

const formatDateTime = (dateTime) => {
  return dayjs(dateTime).format('YYYY-MM-DD HH:mm')
}

const getProgressColor = (rate) => {
  if (rate >= 90) return '#67c23a'
  if (rate >= 70) return '#409eff'
  if (rate >= 50) return '#e6a23c'
  return '#f56c6c'
}

// 快捷选择处理
const handleQuickSelect = (value) => {
  const endDate = dayjs()
  let startDate
  
  switch (value) {
    case '1week':
      startDate = endDate.subtract(1, 'week')
      break
    case '1month':
      startDate = endDate.subtract(1, 'month')
      break
    case '3months':
      startDate = endDate.subtract(3, 'month')
      break
    case '6months':
      startDate = endDate.subtract(6, 'month')
      break
    case '1year':
      startDate = endDate.subtract(1, 'year')
      break
    default:
      startDate = endDate.subtract(1, 'week')
  }
  
  dateRange.value = [startDate.format('YYYY-MM-DD'), endDate.format('YYYY-MM-DD')]
  loadData()
}

// 自定义日期范围变化处理
const handleDateChange = () => {
  quickSelect.value = '' // 清空快捷选择
  loadData()
}

// 加载多领域能力曲线
const loadMultiDomainCurve = async () => {
  loadingCurve.value = true
  try {
    const userId = userStore.userInfo?.userId
    if (!userId || !dateRange.value || dateRange.value.length !== 2) return

    const params = {
      userId,
      startDate: dateRange.value[0],
      endDate: dateRange.value[1]
    }

    const data = await getMultiDomainCurve(params)
    curveData.value = data
    
    // 渲染图表
    await nextTick()
    renderChart(data)
  } catch (error) {
    console.error('加载能力曲线失败:', error)
  } finally {
    loadingCurve.value = false
  }
}

// 加载领域统计
const loadDomainStats = async () => {
  loadingStats.value = true
  try {
    const userId = userStore.userInfo?.userId
    if (!userId || !dateRange.value || dateRange.value.length !== 2) return

    const params = {
      userId,
      startDate: dateRange.value[0],
      endDate: dateRange.value[1]
    }

    const data = await getDomainStats(params)
    domainStats.value = data || []
  } catch (error) {
    console.error('加载领域统计失败:', error)
  } finally {
    loadingStats.value = false
  }
}

// 加载所有数据
const loadData = () => {
  loadMultiDomainCurve()
  loadDomainStats()
}

// 快速访问跳转
const goToTaskHistory = () => {
  router.push('/app/task-history')
}

const goToGrowthBox = () => {
  router.push('/app/growth-box')
}

// 渲染图表
const renderChart = (data) => {
  if (!chartRef.value || !data) return

  if (!chartInstance) {
    chartInstance = echarts.init(chartRef.value)
  }

  // 准备系列数据
  const series = []
  const legendData = []

  // 根据选择的领域过滤数据
  const domains = selectedDomain.value 
    ? [selectedDomain.value] 
    : Object.keys(data.domainData || {})

  domains.forEach(domain => {
    const rates = data.domainData[domain]
    if (rates && rates.length > 0) {
      series.push({
        name: domainNames[domain] || domain,
        type: 'line',
        smooth: true,
        data: rates,
        itemStyle: {
          color: domainColors[domain] || '#409eff'
        },
        lineStyle: {
          width: 3,
          color: domainColors[domain] || '#409eff'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: `${domainColors[domain]}80` || '#409eff80' },
            { offset: 1, color: `${domainColors[domain]}20` || '#409eff20' }
          ])
        }
      })
      legendData.push(domainNames[domain] || domain)
    }
  })

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      },
      textStyle: {
        fontSize: 14
      }
    },
    legend: {
      data: legendData,
      top: 10,
      textStyle: {
        fontSize: 14
      }
    },
    grid: {
      left: '5%',
      right: '4%',
      bottom: '5%',
      top: '60px',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: data.dates || [],
      axisLabel: {
        fontSize: 13,
        color: '#606266'
      },
      axisLine: {
        lineStyle: {
          color: '#e4e7ed'
        }
      }
    },
    yAxis: {
      type: 'value',
      name: '能力得分',
      nameTextStyle: {
        fontSize: 14,
        color: '#303133',
        padding: [0, 0, 0, 10]
      },
      min: 50,
      max: 100,
      interval: 10,
      axisLabel: {
        fontSize: 14,
        color: '#606266',
        formatter: '{value}分'
      },
      axisLine: {
        show: true,
        lineStyle: {
          color: '#e4e7ed'
        }
      },
      splitLine: {
        lineStyle: {
          color: '#f0f2f5',
          type: 'dashed'
        }
      }
    },
    series: series
  }

  chartInstance.setOption(option, true)
}

// 监听领域选择变化
watch(selectedDomain, () => {
  if (curveData.value) {
    renderChart(curveData.value)
  }
})

// 处理窗口大小变化
const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize()
  }
}

onMounted(() => {
  // 初始化默认为近1个月
  handleQuickSelect('1month')
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.filter-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
}

.header-actions {
  display: flex;
  align-items: center;
}

.record-count {
  font-size: 14px;
  color: #909399;
  font-weight: normal;
}

.chart-container {
  width: 100%;
  height: 450px;
}

.stats-container {
  padding: 10px 0;
}

.domain-stat-card {
  padding: 20px;
  background: linear-gradient(135deg, #fff5fb 0%, #fff9f5 100%);
  border-radius: 12px;
  margin-bottom: 20px;
  transition: all 0.3s;
}

.domain-stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
}

.stat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.stat-header h3 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.stat-details {
  display: flex;
  justify-content: space-around;
  gap: 20px;
}

.stat-item {
  text-align: center;
  flex: 1;
}

.stat-item .label {
  display: block;
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.stat-item .value {
  display: block;
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.quick-actions {
  display: flex;
  gap: 15px;
  padding: 20px;
  justify-content: center;
  flex-wrap: wrap;
}

.quick-actions .el-button {
  padding: 15px 30px;
  font-size: 16px;
  border-radius: 8px;
}


@media (max-width: 768px) {
  .chart-container {
    height: 300px;
  }

  .history-header {
    flex-direction: column;
    gap: 15px;
  }

  .history-score {
    width: 100%;
    justify-content: center;
  }

  .domain-stat-card {
    margin-bottom: 15px;
  }

  .stat-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
}
</style>